package com.fly.caihong.base;

import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Pair;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fly.caihong.utils.PageWrapper;
import com.fly.caihong.view.PullRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BasePageListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener {

    protected PullRefreshRecyclerView mPullRefreshView;
    protected PageWrapper mPageWrapper;
    protected BaseQuickAdapter mAdapter;

    @Override
    protected void initView(View view) {
        Pair<PullRefreshRecyclerView, BaseQuickAdapter> pair = initPullRefreshView(view);
        mPullRefreshView = pair.first;
        mAdapter = pair.second;
        mPullRefreshView.setAdapter(mAdapter);
        mPageWrapper = new PageWrapper(mPullRefreshView);
        showRefreshStatus();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mPullRefreshView.setOnRefreshListener(this);
        mPullRefreshView.setOnLoadMoreListener(this);
        mPullRefreshView.setOnItemClickListener(this);
    }

    @Override
    public void onRefresh() {
        resetPagePullRefresh();
        loadPageData(mPageWrapper.getPageNum());
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
    }

    @Override
    public void onLoadMoreRequested() {
        loadPageData(mPageWrapper.getPageNum());
    }

    /**
     * 取消刷新状态
     */
    protected void dismissRefreshStatus() {
        if (mPullRefreshView.isRefreshing()) {
            mPullRefreshView.setRefreshing(false);
        }
    }

    /**
     * 显示刷新状态
     */
    protected void showRefreshStatus() {
        if (!mPullRefreshView.isRefreshing()) {
            mPullRefreshView.setRefreshing(true);
        }
    }

    /**
     * 重置第一页
     */
    protected void resetPagePullRefresh() {
        mPullRefreshView.setNewData(new ArrayList());
        mPageWrapper.resetPageNum();
    }

    /**
     * 获取数据集
     * @return
     */
    protected List getData() {
        return mPullRefreshView.getData();
    }

    /**
     * 分页加载失败
     */
    protected void notifyDataFailure() {
        mPageWrapper.notifyDataFailure();
    }

    /**
     * 分页加载成功
     */
    protected void notifyDataSuccess(List newData) {
        if (mPageWrapper.isFirstPage() && newData.size() < 10) {
            mPullRefreshView.disableLoadMoreIfNotFullPage();
        }
        mPageWrapper.notifyDataSuccess(newData);
    }

    /**
     * 初始化刷新控件
     *
     * @return
     */
    protected abstract Pair<PullRefreshRecyclerView, BaseQuickAdapter> initPullRefreshView(View view);

    /**
     * 分页加载数据
     *
     * @param pageNum
     */
    protected abstract void loadPageData(int pageNum);

}
